package cwb.utils;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Ezio.Auditore
 * @description JWT工具类
 */
@Slf4j
public class JwtUtil {
    /**
     * 设置过期时间及密匙
     * CALENDAR_FIELD 时间单位
     * CALENDAR_INTERVAL 有效时间
     * SECRET_KEY 密匙
     */
    public static final int CALENDAR_FIELD = Calendar.MINUTE;
    public static final int CALENDAR_INTERVAL = 60 * 1;
    private static final String SECRET_KEY = "emm";

    /**
     * 创建Token
     *
     * @param userMap 自己需要存储进token中的信息
     * @return token
     */
    public static String createToken(HashMap<String, Object> userMap) {
        // 头部
        Map<String, Object> headerMap = new HashMap<>(4);
        headerMap.put("alg", "HS256");
        headerMap.put("typ", "JWT");

        // 当前时间与过期时间
        Calendar time = Calendar.getInstance();
        Date now = time.getTime();
        time.add(CALENDAR_FIELD, CALENDAR_INTERVAL);
        Date expireTime = time.getTime();

        // 选择签名加密算法
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);

        // 创建token并返回
        return JWT.create().withHeader(headerMap)
                .withIssuedAt(now)
                .withExpiresAt(expireTime)
                .withSubject("user")
                .withClaim("userInfo", userMap)
                .sign(algorithm);
    }

    /**
     * 验证、解析Token
     *
     * @param token 用户提交的token
     * @return 该token中的信息
     */
    public static Map<String, Object> verifyToken(String token) {
        DecodedJWT verifier = null;
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        try {
            verifier = JWT.require(algorithm).build().verify(token);
        } catch (TokenExpiredException tokenExpiredException) {
            System.out.println("token已经过期");
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert verifier != null;
        return verifier.getClaim("userInfo").asMap();
    }

    public static void main(String[] args) throws InterruptedException {
//        HashMap<String, Object> userMap = new HashMap<>(2);
//        System.out.println("加密token：");
//        userMap.put("userId", "1");
//        userMap.put("userName", "admin");
//        String token = createToken(userMap);
//        System.out.println(token);
//        //Thread.sleep(5000L);
//        System.out.println("解密Token：");
//        Map<String, Object> userInfo = verifyToken(token);
//        System.out.println(userInfo.toString());


        System.out.println(verifyJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXV0b2RlbGl2ZXIiXSwiZXhwIjoxNjYxNTEwMDQzLCJ1c2VyX25hbWUiOiJjd2IiLCJqdGkiOiI5MDNlODAwMS00YjRhLTQ3ZDUtOTdjZC1mZWVhMTk0NDQ3MzMiLCJjbGllbnRfaWQiOiJjbGllbnRfZW1tIiwic2NvcGUiOlsiYWxsIl19.TpQBbCUICYee3QQMXw12mXxy11qvRHFSi6B3bvDkOww"));
    }

    /**
     * 验证、解析Token
     *
     * @param token 用户提交的token
     * @return 该token中的信息
     */
    public static String verifyJWT(String token) {
        DecodedJWT verifier = null;
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        try {
            verifier = JWT.require(algorithm).build().verify(token);
        } catch (TokenExpiredException tokenExpiredException) {
            log.error("token已经过期", tokenExpiredException);
            return null;
        } catch (Exception e) {
            log.error("解析Token出错", e);
        }
        String payLoadJson = new String(Base64.decode(verifier.getPayload().getBytes()));
        System.out.println(payLoadJson);
        Map result = JSONObject.parseObject(payLoadJson, Map.class);
        return (String) result.get("user_name");
    }
}

